/**
 * 通用ajax请求
 * @author 阿城 <479468212@qq.com>
 */

import config from "@/static/js/config.js"
import { getToken,setToken } from "@/static/js/util.js"
import http from '@/common/vmeitime-http/interface.js'
import store from 'store'
	
const apiRequest = (options) => {
	if (!options.url || options.url === '') {
		return false
	}
	let method = 'GET'
	if (options.method) {
		method = options.method
	}
	let data = options.data
	if (config.debug) {
		console.log('请求数据:', JSON.stringify(options))
	}
	//设置请求前拦截器
	http.interceptor.request = (config) => {
		let headers = {
			'Content-Type': 'application/json;charset=UTF-8',
			'App-Client-Version': '1.0',
			'App-Device-Type': 'mobile'
		}
		let token = getToken();
		if (token !== false) {
			headers["App-Login-Token"] = token
		}
		// 附加自定义头部
		if (options.headers) {
			Object.assign(headers, options.headers)
		}
		config.header = headers
	}
	//设置请求结束后拦截器
	http.interceptor.response = (response) => {
		if (config.debug) {
			if (response) {
				console.log('返回结果:', JSON.stringify(response.data))
			}
		}
		let result = response.data;
		if (result && result.code < 0) {
			//授权失败
			if (result.code === -1) {
				store.commit('setToken','');
				store.commit('setUserInfo', {})
				uni.showToast({ title: result.msg, icon: 'none' })
				setTimeout(() => {
					uni.reLaunch({ url: '/pages/main/main' })
				}, 2000)
				return response
			}
			// 系统业务级别报错
			if (result.code === -3) {
				uni.showToast({ title: "系统逻辑错误:"+(result.msg), icon: 'none' })
				return Promise.reject(result)
			}
		}
		//网络通讯异常
		if (response.errMsg === 'request:fail') {
			uni.showToast({ title: '网络异常', icon: 'none' })
			return false
		}
		return response;
	}
	return http.request({
		baseUrl: config.host,
		url: options.url,
		method: method,
		dataType: options.dataType,
		header: options.header,
		data: data
	})
}

export default apiRequest
